//
//  YSTimeUtil.m
//  YSDH
//
//  Created by 王建都 on 2017/9/7.
//  Copyright © 2017年 熊小辉. All rights reserved.
//

#import "YSTimeUtil.h"
#import "NSDate+HYBHelperKit.h"
#define MILLI_SECOND  1000000000000.0

@implementation YSTimeUtil

/**
 获取当前时间戳
 
 @return 当前时间戳
 */
+(NSTimeInterval)getCurrentTick{
    
    NSDate *date=[NSDate date];
    
    return [date timeIntervalSince1970];
}

/**
 获取当前时间（yyyy-MM-dd HH:mm:ss）
 
 @return 获取当前时间
 */
+(NSString *)getCurrentTime{
    
    return [YSTimeUtil getCurrentDate:@"yyyy-MM-dd HH:mm:ss"];
}

/**
 获取今天的日期(yyyy-MM-dd)
 
 @return 获取今天的日期
 */
+ (NSString*)getCurrentDate{
    
    return [YSTimeUtil getCurrentDate:@"yyyy-MM-dd"];
}

/**
 获取当前日期
 
 @param format 格式（eg:yyyy-MM-dd,yyyy.MM.dd，默认yyyy-MM-dd）
 @return 返回当前日期
 */
+ (NSString*)getCurrentDate:(NSString*)format{
    
    if(format.length <= 0){
    
        format = @"yyyy-MM-dd";
    }
    
    NSDate *  senddate = [NSDate date];
    
    NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
    
    [dateformatter setDateFormat:format];
    
    NSString *locationString = [dateformatter stringFromDate:senddate];
    
    return locationString;
}

/**
 获取本周日期（周一开始）
 
 @param format 时间格式（eg:yyyy-MM-dd,yyyy.MM.dd，默认yyyy-MM-dd）
 @return 返回本周日期（format - format）
 */
+ (NSString*)getCurrentWeek:(NSString *)format{
    
    if(format.length <= 0){
        
        format = @"yyyy-MM-dd";
    }

    NSDate *now = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *comp = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitWeekday|NSCalendarUnitDay fromDate:now];
    
    // 得到星期几
    // 1(星期天) 2(星期二) 3(星期三) 4(星期四) 5(星期五) 6(星期六) 7(星期天)
    NSInteger weekDay = [comp weekday];
    
    if(weekDay == 1){
    
        weekDay = 7;
    }else{
    
        --weekDay;
    }
    
    
    // 得到几号
    NSInteger day = [comp day];
    
    // 计算当前日期和这周的星期一和星期天差的天数
    long firstDiff,lastDiff;
    
    firstDiff = weekDay - 1;
    lastDiff = 7 - weekDay;
    
    // 在当前日期(去掉了时分秒)基础上加上差的天数
    NSDateComponents *firstDayComp = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:now];
    [firstDayComp setDay:day - firstDiff];
    NSDate *firstDayOfWeek= [calendar dateFromComponents:firstDayComp];
    
    NSDateComponents *lastDayComp = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:now];
    [lastDayComp setDay:day + lastDiff];
    NSDate *lastDayOfWeek= [calendar dateFromComponents:lastDayComp];
    
    NSDateFormatter *formater = [[NSDateFormatter alloc] init];
    [formater setDateFormat:format];
//    NSLog(@"星期一开始 %@",[formater stringFromDate:firstDayOfWeek]);
//    NSLog(@"当前 %@",[formater stringFromDate:now]);
//    NSLog(@"星期天结束 %@",[formater stringFromDate:lastDayOfWeek]);
    
    return [NSString stringWithFormat:@"%@-%@",[formater stringFromDate:firstDayOfWeek],[formater stringFromDate:lastDayOfWeek]];
}

/**
 获取本月日期（1号开始）
 
 @param format 时间格式（eg:yyyy-MM-dd,yyyy.MM.dd，默认yyyy-MM-dd）
 @return 返回本月日期（format - format）
 */
+ (NSString*)getCurrentMonth:(NSString *)format{

    if(format.length <= 0){
        
        format = @"yyyy-MM-dd";
    }
    
    NSDate *now = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    
    //本月的天数
    NSRange range = [calendar rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:[NSDate date]];
    NSUInteger numberOfDaysInMonth = range.length;
    
    NSDateComponents *firstDayComp = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:now];
    [firstDayComp setDay:1];
    NSDate *firstDayOfMonth = [calendar dateFromComponents:firstDayComp];
    
    NSDateComponents *lastDayComp = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:now];
    [lastDayComp setDay:numberOfDaysInMonth];
    NSDate *lastDayOfMonth = [calendar dateFromComponents:lastDayComp];
    
    NSDateFormatter *formater = [[NSDateFormatter alloc] init];
    [formater setDateFormat:format];
    
    return [NSString stringWithFormat:@"%@-%@",[formater stringFromDate:firstDayOfMonth],[formater stringFromDate:lastDayOfMonth]];
}

/**
 获取本年日期（1月1号开始）
 
 @param format 时间格式（eg:yyyy-MM-dd,yyyy.MM.dd，默认yyyy-MM-dd）
 @return 返回本年日期（format - format）
 */
+ (NSString*)getCurrentYear:(NSString *)format{

    if(format.length <= 0){
        
        format = @"yyyy-MM-dd";
    }
    
    NSString* year = [YSTimeUtil getCurrentYear];
    
    NSString* firstString = [[[format stringByReplacingOccurrencesOfString:@"yyyy" withString:year] stringByReplacingOccurrencesOfString:@"MM" withString:@"01"] stringByReplacingOccurrencesOfString:@"dd" withString:@"01"];
    
    NSString* lastString = [[[format stringByReplacingOccurrencesOfString:@"yyyy" withString:year] stringByReplacingOccurrencesOfString:@"MM" withString:@"12"] stringByReplacingOccurrencesOfString:@"dd" withString:@"31"];
    
    return [NSString stringWithFormat:@"%@-%@",firstString,lastString];
}

/**
 获取当前年份

 @return 当前年份
 */
+(NSString *)getCurrentYear{
    
    NSDate *date = [NSDate date];
    NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy"];
    return [formatter stringFromDate:date];
}

/**
 获取某年某月的天数

 @param year 年份
 @param month 月份
 @return 天数
 */
+(NSInteger)howManyDaysInThisYear:(NSInteger)year withMonth:(NSInteger)month{
    if((month == 1) || (month == 3) || (month == 5) || (month == 7) || (month == 8) || (month == 10) || (month == 12))
        return 31 ;
    
    if((month == 4) || (month == 6) || (month == 9) || (month == 11))
        return 30;
    
    if((year % 4 == 1) || (year % 4 == 2) || (year % 4 == 3))
    {
        return 28;
    }
    
    if(year % 400 == 0)
        return 29;
    
    if(year % 100 == 0)
        return 28;
    
    return 29;
}

/**
 根据时间串获取时间戳

 @param string 时间串
 @return 返回时间戳
 */
+ (NSTimeInterval)timeStmpFromYMDHMS:(NSString*)string{
    
    NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
    
    [dateformatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    NSDate * date = [dateformatter dateFromString:string];
    
    return  date.timeIntervalSince1970;
}

/**
 根据时间串获取时间（NSDate）

 @param timeSting 时间串
 @param format 时间格式
 @return NSDate
 */
+(NSDate*)dateWithTimeString:(NSString*)timeSting format:(NSString*)format{

    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:format];
    
    return [formatter dateFromString:timeSting];
}

/**
 获取当前时间，x年x月x天后的时间
 
 @param year 年数
 @param month 月数
 @param day 天数
 @return 新的时间串
 */
+(NSString*)timeStringAfter:(NSInteger)year month:(NSInteger)month day:(NSInteger)day format:(NSString*)format{
    
    NSDate *nowDate = [NSDate date];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    
    [formatter setDateFormat:format];
    
    return [YSTimeUtil timeStringAfter:[formatter stringFromDate:nowDate] year:year month:month day:day format:format];
}

/**
 获取dateString，x年x月x天后的时间
 
 @param year 年数
 @param month 月数
 @param day 天数
 @param format 时间格式
 @return 新的时间串
 */
+(NSString*)timeStringAfter:(NSString*)dateString year:(NSInteger)year month:(NSInteger)month day:(NSInteger)day format:(NSString*)format{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    
    [formatter setDateFormat:format];
    
    NSDate* date = [formatter dateFromString:dateString];
    
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    
    NSDateComponents *comps = nil;
    
    comps = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:date];
    
    NSDateComponents *adcomps = [[NSDateComponents alloc] init];
    
    [adcomps setYear:year];
    
    [adcomps setMonth:month];
    
    [adcomps setDay:day];
    
    NSDate *newdate = [calendar dateByAddingComponents:adcomps toDate:date options:0];
    
    return [formatter stringFromDate:newdate];
}

+(NSString*)getTimeStringWithDate:(NSDate*)date format:(NSString*)format{
    if (!date) {
        return nil;
    }
    if(format.length <= 0){
        format = @"yyyy-MM-dd";
    }
    
    NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
    
    [dateformatter setDateFormat:format];
    
    NSString *locationString = [dateformatter stringFromDate:date];
    
    return locationString;
}

//时间time1，time2大小比较
+(NSComparisonResult)compareTime:(NSString*)time1 time:(NSString*)time2 format:(NSString*)dataFormat{
    
    NSDateFormatter * format = [[NSDateFormatter alloc]init];
    
    format.dateFormat = dataFormat;
    
    NSDate * date1 = [format dateFromString:time1];
    
    NSDate * date2 = [format dateFromString:time2];
    
    NSComparisonResult result = [date1 compare:date2];
    
    return result;
}

/**
 获取星期几（周日是第一天）

 @param dayOfWeek 第几天
 @return 星期X
 */
+(NSString*)weekdayStr:(NSInteger)dayOfWeek{
    
    static NSDictionary *daysOfWeekDict = nil;
    daysOfWeekDict = @{@(1):@"星期日",@(2):@"星期一",@(3):@"星期二",@(4):@"星期三",@(5):@"星期四",@(6):@"星期五",@(7):@"星期六",};
    return [daysOfWeekDict objectForKey:@(dayOfWeek)];
}

/**
 获取一天时间点的所在时段

 @param time 小时
 @param minute 分钟
 */
+ (NSString *)getPeriodOfTime:(NSInteger)time withMinute:(NSInteger)minute{
    
    NSInteger totalMin = time *60 + minute;
    NSString *showPeriodOfTime = @"";
    if (totalMin > 0 && totalMin <= 5 * 60)
    {
        showPeriodOfTime = @"凌晨";
    }
    else if (totalMin > 5 * 60 && totalMin < 12 * 60)
    {
        showPeriodOfTime = @"上午";
    }
    else if (totalMin >= 12 * 60 && totalMin <= 18 * 60)
    {
        showPeriodOfTime = @"下午";
    }
    else if ((totalMin > 18 * 60 && totalMin <= (23 * 60 + 59)) || totalMin == 0)
    {
        showPeriodOfTime = @"晚上";
    }
    return showPeriodOfTime;
}

/**
 获取beginTime和endTime的时间差
 
 @param beginTime 开始时间
 @param endTime 结束时间
 @param dataFormat 时间格式
 */
+ (NSTimeInterval)getIntervalBetweenTime:(NSString*)beginTime endTime:(NSString*)endTime format:(NSString*)dataFormat{
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    
    [dateFormatter setDateFormat:dataFormat];
    
    NSDate *date1 = [dateFormatter dateFromString:beginTime];
    
    NSDate *date2 = [dateFormatter dateFromString:endTime];
    
    NSTimeInterval time = [date2 timeIntervalSinceDate:date1];
    
    return time;
}

/**
 获取当前时间到和endTime的时间差
 
 @param endTime 结束时间
 @param dataFormat 时间格式
 */
+ (NSTimeInterval)getIntervalToTime:(NSString*)endTime format:(NSString*)dataFormat{
    
    return [YSTimeUtil getIntervalBetweenTime:[YSTimeUtil getCurrentDate:dataFormat] endTime:endTime format:dataFormat];
}

+ (NSString*)timeStrWith:(NSTimeInterval)timeInterval format:(NSString*)format{
    
    NSDate * date = [NSDate dateWithTimeIntervalSince1970:timeInterval];    
    return [date hyb_stringWithFormat:format];
}

+ (NSString*)timeStrWith:(NSTimeInterval)timeInterval{
    if (timeInterval > MILLI_SECOND) {
        timeInterval = timeInterval / 1000.0;
    }
    
    NSDate * date = [NSDate dateWithTimeIntervalSince1970:timeInterval];
    if (date.hyb_isToday) {
        return [self timeStrWith:timeInterval format:@"HH:mm"];
    }else{
        return [self timeStrWith:timeInterval format:@"yyyy/M/d HH:mm"];
    }
}

+ (BOOL)isToday:(NSTimeInterval)timeInterval{
    
    NSDate * date = [NSDate dateWithTimeIntervalSince1970:timeInterval];
    return date.hyb_isToday;
}



#pragma mark - 将某个时间戳转化成 时间
+(NSString *)timestampSwitchTime:(NSInteger)timestamp andFormatter:(NSString *)format{

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];

    [formatter setDateStyle:NSDateFormatterMediumStyle];

    [formatter setTimeStyle:NSDateFormatterShortStyle];

    [formatter setDateFormat:format]; // （@"yyyy-MM-dd hh:mm:ss"）----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制

    NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];

    [formatter setTimeZone:timeZone];

    NSDate *confromTimesp = [NSDate dateWithTimeIntervalSince1970:timestamp];

    NSString *confromTimespStr = [formatter stringFromDate:confromTimesp];

    return confromTimespStr;
}


+ (NSString *)getTime: (NSInteger)hour andMinute:(NSInteger)minute {
    NSCalendar *greCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];

    NSTimeZone *timeZone = [[NSTimeZone alloc] initWithName:@"Asia/Shanghai"];
    [greCalendar setTimeZone: timeZone];

    NSDateComponents *dateComponents = [greCalendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay  fromDate:[NSDate date]];
    //  定义一个NSDateComponents对象，设置一个时间点
    NSDateComponents *dateComponentsForDate = [[NSDateComponents alloc] init];
    [dateComponentsForDate setDay:dateComponents.day];
    [dateComponentsForDate setMonth:dateComponents.month];
    [dateComponentsForDate setYear:dateComponents.year];
    [dateComponentsForDate setHour:hour];
    [dateComponentsForDate setMinute:minute];

    NSDate *dateFromDateComponentsForDate = [greCalendar dateFromComponents:dateComponentsForDate];
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[dateFromDateComponentsForDate timeIntervalSince1970]];
    return timeSp;
}


+ (NSString*)weekdayStringFromDate:(NSDate*)inputDate {
    
    NSArray *weekdays = [NSArray arrayWithObjects: [NSNull null], @"周日", @"周一", @"周二", @"周三", @"周四", @"周五", @"周六", nil];
    
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    
    NSTimeZone *timeZone = [[NSTimeZone alloc] initWithName:@"Asia/Shanghai"];
    
    [calendar setTimeZone: timeZone];
    
    NSCalendarUnit calendarUnit = NSCalendarUnitWeekday;
    
    NSDateComponents *theComponents = [calendar components:calendarUnit fromDate:inputDate];
    
    return [weekdays objectAtIndex:theComponents.weekday];
    
}



// 字符串时间—>时间戳->年月日
+ (NSString *)cTimestampFromString:(NSString *)theTime {
    if ([theTime isKindOfClass:[NSNull class]]) {
        return @"";
    }
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate* dateTodo = [formatter dateFromString:theTime];
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[dateTodo timeIntervalSince1970]];
    return timeSp;
}


+ (NSString *)cTimestampFromTwoString:(NSString *)theTime {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"yyyy/MM/dd HH:mm"];
    NSDate* dateTodo = [formatter dateFromString:theTime];
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[dateTodo timeIntervalSince1970]];
    return timeSp;
}


+ (NSString *)cTimestampFromYearMonthDayString:(NSString *)yearMonthDayTime
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSDate* dateTodo = [formatter dateFromString:yearMonthDayTime];
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[dateTodo timeIntervalSince1970]];
    return timeSp;
}


/**
 获取周几
 
 @param timeStamp 时间戳(秒为单位)
 */
+ (NSString*)weekdayStringWithFromDate:(NSString *)timeStamp
 {
    NSDate *nd = [NSDate dateWithTimeIntervalSince1970:(NSTimeInterval)[timeStamp doubleValue]];
   NSArray *weekdays = [NSArray arrayWithObjects: [NSNull null], @"星期日", @"星期一", @"星期二", @"星期三", @"星期四", @"星期五", @"星期六",  nil];
    
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSTimeZone *timeZone = [[NSTimeZone alloc] initWithName:@"Asia/Shanghai"];
    
    [calendar setTimeZone: timeZone];
    
    NSCalendarUnit calendarUnit = NSCalendarUnitWeekday;
    
    NSDateComponents *theComponents = [calendar components:calendarUnit fromDate:nd];
    
    return [weekdays objectAtIndex:theComponents.weekday];
    
}

/**
 获取日前（1.当天的消息，只显示该消息的时、分
         2.昨日的消息，显示为“昨天”
         3.昨日之前（不包括昨日），本周一（包括本周一）之后的消息，显示为“星期几”  4.本周之前的消息，显示为年/月/日  例：2021/11/19）
 
 @param timeStamp 传入时间戳(秒为单位)
 */
+ (NSString *)getNoticeDate:(NSString *)timeStamp
{
    if (!(timeStamp.integerValue > 0)) {
        return @"";
    }
    //timeStamp时间戳转成NSDate数据类型
    NSDate *tempDate = [NSDate dateWithTimeIntervalSince1970:(NSTimeInterval)[timeStamp doubleValue]];
    //星期几
    NSString *weekStr = [self weekdayStringWithFromDate:timeStamp];
    //当天零点的时间戳
    NSString *todayTimeStamp = [self getTime:0 andMinute:0];
    //昨天零点的时间戳
    NSInteger yesterdayTimeStamp = [todayTimeStamp integerValue] - 86400;
    //明天零点的时间戳
    NSString *nextTimeStamp = [NSString stringWithFormat:@"%ld",(long)[todayTimeStamp integerValue] + 86400];
    if ([timeStamp integerValue] > [todayTimeStamp integerValue] && [timeStamp integerValue] < [nextTimeStamp integerValue])
    {
        //当天的消息
        return [self timestampSwitchTime:[timeStamp integerValue] andFormatter:@"HH:mm"];
    }
    else if ([timeStamp integerValue] > yesterdayTimeStamp && [timeStamp integerValue] < [todayTimeStamp integerValue])
    {
        //昨日的消息
        return @"昨天";
    }
    else if ([self isSameWeekWithDate:tempDate])
    {
        return weekStr;
    }
    else
    {
        return [self timestampSwitchTime:[timeStamp integerValue] andFormatter:@"yyyy/MM/dd"];
    }
}


/**
 判断某个时间是不是属于本周
 
 @param toDate  NSDate数据
 */
+ (BOOL)isSameWeekWithDate:(NSDate *)toDate{
    // 日历对象
    NSCalendar *calendar = [NSCalendar currentCalendar];
    calendar.firstWeekday = 2;
    unsigned unitFlag = NSCalendarUnitYear | NSCalendarUnitWeekOfYear;
    NSDateComponents *comp1 = [calendar components:unitFlag fromDate:[NSDate date]];
    NSDateComponents *comp2 = [calendar components:unitFlag fromDate:toDate];
    return (([comp1 year] == [comp2 year]) && ([comp1 weekOfYear] == [comp2 weekOfYear]));
}


/**
 *  NSDate转时间戳
 *
 *  @param date 字符串时间
 *
 *  @return 返回时间戳
 */
+ (NSString *)cTimestampFromDate:(NSDate *)date
{
    NSTimeInterval timeInterval = [date timeIntervalSince1970];
    
    NSString *result = [NSString stringWithFormat:@"%.0f",timeInterval];
    
    return result;
}
@end
